<?php
namespace app\web\controller;

use think\Db; 
use app\web\model\TaskCase as TaskCaseModel;
use app\web\model\TaskItem as TaskItemModel;
use app\web\model\TaskItemNote as TaskItemNoteModel;
use app\web\model\User;
class Task extends Base{

	public function index(){
		echo "index";
	}
	/*
	未完成
	*/
    public function unfinished()
	{
		$mtaskcase = new TaskCaseModel();
		//按未完成量排序
		if(session('user_auth')['uid'] == 1){
			//按未完成量排序
			$waitlist = Db::name('task_case_user')->order('count desc')->limit(200)->select();//admin查看所有
		}else{
			$waitlist = Db::name('task_case_user')->where('uid', session('user_auth')['uid'])->order('count desc')->select();
		}

		
		foreach ($waitlist as $key => $value) {
			$listid[$key] = $value['case_id']; 
		}
		$caselist = array();
		if(isset($listid)){
			$caselist = $mtaskcase->where('id','in',$listid)->where('status',1)->whereOr('type',2)->order('create_time desc')->select();//按ID数组查询
		}else{
			//自己没有也要去找全员类的
			$caselist = $mtaskcase->where('type',2)->order('create_time desc')->select();//按ID数组查询
		}
		foreach ($caselist as $key => $value) {
			$tcuw = Db::name('task_case_user')->where('case_id', $value['id'])->where('uid', session('user_auth')['uid'])->find();
			//if(!empty($tcuw))
			$caselist[$key]['wait'] = $tcuw['count'];//未完成数量 
			$caselist[$key]['star'] = $tcuw['star'];//未完成数量 
			$caselist[$key]['notice'] = $tcuw['notice'];//提醒数量 
			$caselist[$key]['team_info'] = $this->get_case_team_info($value['id']);
		}
		//var_dump($caselist);
		$this->assign('caselist',$caselist);
		$this->assign('title',"未完成项目");
		return view('my');
	}
	/*
	加星项目
	*/
    public function star()
	{
		$mtaskcase = new TaskCaseModel();

		//按未完成量排序
		$waitlist = Db::name('task_case_user')->where('uid', session('user_auth')['uid'])->where('star',1)->order('count desc')->limit(50)->select();
		foreach ($waitlist as $key => $value) {
			$listid[$key] = $value['case_id']; 
		}
		$caselist = array();
		if(isset($listid)){
			$caselist = $mtaskcase->where('id','in',$listid)->order('create_time desc')->select();//按ID数组查询

		}
		foreach ($caselist as $key => $value) {
			$tcuw = Db::name('task_case_user')->where('case_id', $value['id'])->where('uid', session('user_auth')['uid'])->find();
			//if(!empty($tcuw))
			$caselist[$key]['wait'] = $tcuw['count'];//未完成数量 
			$caselist[$key]['star'] = $tcuw['star'];//未完成数量 
			$caselist[$key]['notice'] = $tcuw['notice'];//提醒数量 
			$caselist[$key]['team_info'] = $this->get_case_team_info($value['id']);
		}
		//var_dump($caselist);
		$this->assign('caselist',$caselist);
		$this->assign('title',"我的加星项目");
		return view('my');
	}
	/*
	已完成项目
	*/
	public function my(){
		$mtaskcase = new TaskCaseModel();
		if(session('user_auth')['uid'] == 1){
			//按未完成量排序
			$waitlist = Db::name('task_case_user')->order('count desc')->limit(200)->select();
		}else{
			//按未完成量排序
			$waitlist = Db::name('task_case_user')->where('uid', session('user_auth')['uid'])->order('count desc')->limit(50)->select();
		}
		foreach ($waitlist as $key => $value) {
			$listid[$key] = $value['case_id']; 
		}

		$caselist = array();
		if(isset($listid)){
			$caselist = $mtaskcase->where('id','in',$listid)->where('status',2)->order('create_time desc')->select();//按ID数组查询
		}
		foreach ($caselist as $key => $value) {
			$tcuw = Db::name('task_case_user')->where('case_id', $value['id'])->where('uid', session('user_auth')['uid'])->find();
			//if(!empty($tcuw))
			$caselist[$key]['wait'] = $tcuw['count'];//未完成数量 
			$caselist[$key]['star'] = $tcuw['star'];//未完成数量 
			$caselist[$key]['notice'] = $tcuw['notice'];//提醒数量 
			$caselist[$key]['team_info'] = $this->get_case_team_info($value['id']);
		}
		//var_dump($caselist);
		$this->assign('caselist',$caselist);
		$this->assign('title',"已完成项目");
		return view('my');
	}

	public function case_view(){
		$mtaskcase = new TaskCaseModel();
		$mtaskitem = new TaskItemModel();
		$mtaskitemnote = new TaskItemNoteModel();
		$uid =  session('user_auth')['uid'];
		//echo input('id');
		$caseinfo = $mtaskcase->get(input('id'));

		$manage = Db::name('User')->where('id',$caseinfo['manage_uid'])->find();
		$caseinfo['manage_username'] = $manage['username'];
		//用户列表
		$userlist = Db::name('User')->select();
		//查看用户对应项目的信息
		$tcuw = Db::name('task_case_user')->where('case_id', input('id'))->where('uid', session('user_auth')['uid'])->find();
		$caseinfo['wait'] = $tcuw['count'];//未完成数量 
		$caseinfo['star'] = $tcuw['star'];//未完成数量 

		//清除提醒标记
		Db::name('task_case_user')
			->where('uid','=',session('user_auth')['uid'])
			->where('case_id','=',input('id'))
			->update([
				'notice' => 0,
			]);

		//未完成列表
		$itemlist = $mtaskitem->where('case_id',input('id'))->where('status',0)->order('create_time desc')->limit(50)->select();
		foreach ($itemlist as $key => $value) {
			$itemlist[$key]['note'] = $mtaskitemnote->where('iid',$value['id'])->select();
			$itemlist[$key]['note_count'] = count($itemlist[$key]['note']);//获取备注个数
			//当前用户是否设置了隐藏备注
			unset($Arr);
			$Arr = explode(',', $value['user_hide']);//字符串打散为数组
			if(in_array($uid,$Arr)){
				$itemlist[$key]['hide'] = 1;
			}else{
				$itemlist[$key]['hide'] = 0;
			}
		}

		//已完成列表
		$enditemlist = $mtaskitem->where('case_id',input('id'))->where('status',1)->order('create_time desc')->limit(50)->select();
		foreach ($enditemlist as $key => $value) {
			$enditemlist[$key]['note'] = $mtaskitemnote->where('iid',$value['id'])->select();
			$enditemlist[$key]['note_count'] = count($enditemlist[$key]['note']);//获取备注个数
			//当前用户是否设置了隐藏备注
			unset($Arr);
			$Arr = explode(',', $value['user_hide']);//字符串打散为数组
			if(in_array($uid,$Arr)){
				$enditemlist[$key]['hide'] = 1;
			}else{
				$enditemlist[$key]['hide'] = 0;
			}
		}
		//团队成员
		$this->assign('team_info',$this->get_case_team_info(input('id')));

		$this->assign('caseinfo',$caseinfo);
		$this->assign('userlist',$userlist);
		$this->assign('itemlist',$itemlist);
		$this->assign('enditemlist',$enditemlist);
		return view('case_view');
	}
	public function case_create(){
		$mtaskcase = new TaskCaseModel();
		if(request()->isPost() && input('post.')){
			$data['title'] = input('post.title');
			$data['description'] = input('post.description');
			$data['no'] = $this->get_no();//编号
			$data['type'] = input('post.type');//项目类型
			if($mtaskcase->save($data)){
				//成功继续新增一条任务(给自己)
				unset($data);
				$mtaskitem = new TaskItemModel();
				$data['case_id'] = $mtaskcase->id;
				$data['title'] = "请尽快完成项目相关信息和任务安排";
				$data['exe_uid'] = session('user_auth')['uid'];
				$data['type'] = 0;
				$data['no'] = $this->get_no();//编号
				$data['have_read'] = 1;
				$mtaskitem->save($data);
				$this->update_time_item($mtaskitem->id);//更新任务更新时间
				return $this->success('添加成功','task/case_create');
			}else{
				return $this->error($mtaskcase->getError());
			}
		}else{
			return view('case_create');
		}
		
	}
    /*
    新增案子
    */
	public function case_edit(){
		//echo input('id');
        $mtaskcase = new TaskCaseModel();
		if(request()->isPost() && input('post.')){
			$data['title'] = input('post.title');
			$data['description'] = input('post.description');
			$data['type'] = input('post.type');
			if($mtaskcase->where('id', input('id'))->update($data)){
				return $this->success('修改成功','task/case_edit'."&id=".input('id'));
			}else{
				return $this->error($mtaskcase->getError(),'task/case_edit'."&id=".input('id'));
			}
		}else{
			$info = $mtaskcase->get(input('id'));
			$this->assign('info',$info);
			return view('case_create');
		}
	}
	/*
	项目加星
	*/
	public function case_ajax_star(){
		if($tcuw = Db::name('task_case_user')->where('case_id', input('case_id'))->where('uid', session('user_auth')['uid'])->find()){
			Db::name('task_case_user')
				->where('id', $tcuw['id'])
				->update(['star' => 1]);
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
	/*
	项目取消加星
	*/
	public function case_ajax_unstar(){
		if($tcuw = Db::name('task_case_user')->where('case_id', input('case_id'))->where('uid', session('user_auth')['uid'])->find()){
			Db::name('task_case_user')
				->where('id', $tcuw['id'])
				->update(['star' => 0]);
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
	public function help(){
		return view('help');
	}
    /*
	新增任务
    */
	public function item_ajax_create(){
		//echo "index";
		$mtaskitem = new TaskItemModel();
		$data['case_id'] = input('case_id');
		$data['title'] = input('title');
		$data['exe_uid'] = input('exe_uid');
		$data['type'] = input('type');
		$data['no'] = "0";//$this->get_no();//2016-12-15更新1、项目按月做单号，项目取消单号概念

		//自己给自己的任务自动已读
		if(input('exe_uid') == session('user_auth')['uid']){
			$data['have_read'] = 1;
		}else{
			$data['have_read'] = 0;
		}
		if($mtaskitem->save($data)){
			$this->update_time_item($mtaskitem->id);//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		
		return json($ret);
	}
    /*
	完成任务
    */
	public function item_ajax_close(){
		$mtaskitem = new TaskItemModel();
		if($mtaskitem->where('id', input('id'))->update(['status' => 1,'end_time'=>time()])){
			$this->update_time_item(input('id'));//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
    /*
	重新打开
    */
	public function item_ajax_open(){
		$mtaskitem = new TaskItemModel();
		if($mtaskitem->where('id', input('id'))->update(['status' => 0])){
			$this->update_time_item(input('id'));//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
    /*
	取消任务
    */
	public function item_ajax_cancel(){
		$mtaskitem = new TaskItemModel();
		if($mtaskitem->where('id', input('id'))->update(['status' => 1,'cancel'=>1])){
			$this->update_time_item(input('id'));
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
    /*
	已读按钮-任务
    */
	public function item_ajax_read(){
		$mtaskitem = new TaskItemModel();
		if($mtaskitem->where('id', input('id'))->update(['have_read' => 1])){
			$this->update_time_item(input('id'));//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
    /*
	隐藏任务备注
	0=不隐藏
	1=隐藏
    */
	public function item_note_hide(){
		$mtaskitem = new TaskItemModel();
		$info = $mtaskitem->find(input('id'));
		$uid = session('user_auth')['uid'];
		//当前隐藏的用户列表
		$Arr = explode(',', $info['user_hide']);//字符串打散为数组
		$in = in_array($uid,$Arr);//当前是否在隐藏用户清单中
		//隐藏
		if(input('hide') == 1){
			//还不在就添加进去
			if(!$in){
				$Arr[] = $uid;
				$str = implode(',', $Arr);//数组-字符串
				$mtaskitem->where('id', input('id'))->update(['user_hide' => $str]);//更新到数据库
			}
		//恢复显示
		}else{
			$Arr2[] = $uid;
			$str = implode(',', array_diff($Arr2, $Arr));//比较数组，扣除自己的
			$mtaskitem->where('id', input('id'))->update(['user_hide' => $str]);//更新到数据库
		}
		return $in;
	}
    /*
    添加文件
    */
	public function add_upload_to_item(){
		$mtaskitemnote = new TaskItemNoteModel();
		$data['aid'] = input('fid');
		$data['iid'] = input('item_id');
		$data['note'] = "";
		if($mtaskitemnote->save($data)){
			$this->update_time_item(input('item_id'));//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}
    /*
    添加备注
    */
	public function add_note_to_item(){
		$mtaskitemnote = new TaskItemNoteModel();
		$data['aid'] = 0;
		$data['iid'] = input('item_id');
		$data['note'] = input('note');
		if($mtaskitemnote->save($data)){
			$this->update_time_item(input('item_id'));//更新任务更新时间
			$ret['status'] = 1;
		}else{
			$ret['status'] = 0;
		}
		return json($ret);
	}


	public function get_no(){
        //生成默认的工单号，递增
        //$mtask_no = M("task_no");
        $month = date("Ym");
        $map['month'] = $month;
        $num = Db::name('task_no')->where($map)->count() + 1;
		Db::name('task_no')->insert($map);
        return $month . sprintf("%03d",$num);
	}	
	//根据ID更新任务状态
	public function update_time_item($id){
		$mtaskitem = new TaskItemModel();
		$mtaskitem->where('id', $id)->update(['update_time' => time()]);
		$info = $mtaskitem->find($id);

		//
		$this->update_progress_case($info['case_id']);
		$this->case_update_notice($info['case_id']);//更新除自己外另外人员的提醒数目
	}
	//更新除自己外另外人员的提醒数目
    public function case_update_notice($id)
	{
		Db::name('task_case_user')
			->where('uid','<>',session('user_auth')['uid'])
			->where('case_id','=',$id)
			->setInc('notice');
	}
	//更新指定任务对应项目进度
	//包含成员列表
	//根据项目类型，全员，项目，其他等处理方式可能不同
	public function update_progress_case($id){
		$mtaskitem = new TaskItemModel();
		$mtaskcase = new TaskCaseModel();
		
		$all = $mtaskitem->where('case_id', $id)->count();
		$end = $mtaskitem->where('case_id', $id)->where('status', 1)->count();
		$progress = $end*100 / $all;
		if($all == $end){
			$status = 2;
		}else{
			$status = 1;
		}
		//更新项目信息
		$mtaskcase->where('id', $id)->update(['update_time' => time(),'update_uid'=>session('user_auth')['uid'],'all_num'=>$all,'over_num'=>$end,'progress'=>$progress,'status'=>$status]);

		//计算项目中参与人员没人未完成数据量。
		//task_case_user
		//查询当前项目中任务列表中不重复的用户
		$userlist = Db::name('task_item')->distinct(true)->field('exe_uid')->where('case_id', $id)->select();
		foreach ($userlist as $key => $value) {
			$uid = $value['exe_uid'];
			$all = $mtaskitem->where('exe_uid', $uid)->where('case_id', $id)->count();
			$end = $mtaskitem->where('exe_uid', $uid)->where('case_id', $id)->where('status', 1)->count();
			//更新未完成量
			if($tcuw = Db::name('task_case_user')->where('case_id', $id)->where('uid', $uid)->find()){
				Db::name('task_case_user')
    				->where('id', $tcuw['id'])
    				->update(['count' => $all-$end]);
			}else{
				$data = ['uid' => $uid, 'case_id' => $id,'count'=>$all-$end];
				Db::name('task_case_user')->insert($data);
			}
		}
	}
	//获取项目相关人员的列表
	//全员项目则显示“全员”
	public function get_case_team_info($id){
		$mtaskcase = new TaskCaseModel();
		$info = $mtaskcase->find($id);//获取项目信息
		if($info['type'] == 2){
			//全员
			return '<small class="label label-warning">全员</small>&nbsp;&nbsp;';
		}else{
			//不是全员则输出列表
			$userlist = Db::name('task_item')->distinct(true)->field('exe_uid')->where('case_id', $id)->select();
			foreach ($userlist as $key => $value) {
				$listid[$key] = $value['exe_uid']; 
			}
			$muser = new User();
			$list = $muser->where('id','in',$listid)->select();//按ID数组查询
			$str = "";
			foreach ($list as $key => $value) {
				$str .= '<small class="label label-info">'.$value['username'].'</small>&nbsp;&nbsp;';
			}
			//echo $str;
			return $str;
		}

	}
}